package net.airtheva.uniqueTask2.fragment;

import java.util.ArrayList;
import java.util.HashMap;

import net.airtheva.uniqueTask2.R;
import net.airtheva.uniqueTask2.UserActivity;
import net.airtheva.uniqueTask2.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class FollowersFragment extends ListFragment implements IUserFragment {

	ArrayList<HashMap<String, Object>> mFollowers = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_followers, container, false);
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		Update();
		
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		Log.v("FollowersFragment", mFollowers.get(position).get("userId").toString());
		((UserActivity) getActivity()).ViewUser((Integer) mFollowers.get(position).get("userId"));
		
		super.onListItemClick(l, v, position, id);
		
	}

	public void Update() {
		
		try {
			UserActivity activity = (UserActivity) getActivity();
			activity.LoadFollowers();
			JSONArray followers = activity.GetFollowers();
			
			mFollowers = new ArrayList<HashMap<String,Object>>();
			
			for(int i = 0; i < followers.length(); i++) {
				JSONObject follower = followers.getJSONObject(i);
				HashMap<String, Object> item = new HashMap<String, Object>();
				item.put("userId", follower.getInt("id"));
				item.put("iconUri", Utils.CacheIconImage(activity, follower.getString("iconUri")));
				item.put("nickname", follower.getString("nickname"));
				item.put("tweetAmount", follower.getJSONArray("tweets").length());
				item.put("followerAmount", follower.getJSONArray("followers").length());
				mFollowers.add(item);
			}
			
			getListView().setAdapter(new SimpleAdapter(getActivity(), mFollowers, R.layout.follower_item, new String[] { "iconUri", "nickname", "tweetAmount", "followerAmount" }, new int[] { R.id.follower_item_icon, R.id.follower_item_nickname, R.id.follower_item_tweetAmount, R.id.follower_item_followerAmount }));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
